"use strict";

class ImportMetaPlugin {
  /**
   * @param {import('@rspack/core').Compiler} compiler
   */
  apply(compiler) {
    compiler.hooks.thisCompilation.tap("ImportMetaPlugin", (compilation) => {
      compilation.hooks.optimizeTree.tap("ImportMetaPlugin", (chunks) => {
        for (const chunk of chunks) {
          for (const file of chunk.files) {
            if (file.endsWith(".js")) {
              const asset = compilation.assets[file];
              let source = asset.source().toString();

              // 替换占位符为实际文件名逻辑
              source = source.replaceAll(
                "import.meta.filename",
                `/* ImportMetaPlugin Inject */${file}`,
              );

              compilation.assets[file] = new compiler.webpack.sources.RawSource(
                source,
              );
            }
          }
        }
      });
    });
  }
}

module.exports = { ImportMetaPlugin };
